package org.freedoit.client;

import org.freedoit.shared.exception.ServerException;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;

public class RegisterWidget extends Composite {

	private static RegisterWidgetUiBinder uiBinder = GWT
			.create(RegisterWidgetUiBinder.class);
	@UiField Label lblPassword;
	@UiField Label lblPasswordConfirm;
	@UiField PasswordTextBox pwPassword;
	@UiField PasswordTextBox pwPasswordConfirm;
	@UiField Button btnRegister;
	@UiField Button btnCancel;
	@UiField Label lblUserName;
	@UiField TextBox tbUserName;
	@UiField Label lblError;

	interface RegisterWidgetUiBinder extends UiBinder<Widget, RegisterWidget> {
	}

	private final RegisterServiceAsync registerService = GWT
			.create(RegisterService.class);

	public RegisterWidget() {
		initWidget(uiBinder.createAndBindUi(this));
	}
	@UiHandler("btnRegister")
	void onBtnRegisterClick(ClickEvent event) {
		lblError.setText(""); // clear error message if exists

		// Check user name
		String username = tbUserName.getText();
		if (username == null || username.length() == 0)
		{
			lblError.setText("User Name Required");
			return;
		}
		
		String password = pwPassword.getText();
		if (password == null || password.length() == 0)
		{
			lblError.setText("Password Required");
			return;
		}
		
		String passwordConfirmed = pwPasswordConfirm.getText();
		if (!password.equals(passwordConfirmed))
		{
			lblError.setText("Password must be same");
			return;
		}
		
		registerService.register(username, password, new AsyncCallback<String>() {

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				if (caught instanceof ServerException) {
					lblError.setText("Internal Server Error");
				} else {
					lblError.setText(caught.getMessage());
				}
			}

			public void onSuccess(String result) {
				// TODO Auto-generated method stub
				lblError.setText(result);
			}
			
		});
	}
}
